# Load libraries 
library(dplyr)
library(tidyr)
library(glmmTMB)
library(texreg)
library(marginaleffects) 

# Load data on bills and motions:
sponsor_data_bills <- readRDS("MP_sponsored_bills.R")
sponsor_data_motions <- readRDS("MP_sponsored_motions.R")
bills_and_motions <- rbind(sponsor_data_bills, sponsor_data_motions)

bills_and_motions_full <- read.csv("bills_and_motions_full.csv")

################################################################################################
#### Data Cleaning
################################################################################################

# Calculate party median, distance from party, distance from floor
bills_and_motions <- bills_and_motions_full %>%
  group_by(session, party) %>%
  mutate(
    party.median.1D = median(coord1D, na.rm = TRUE),
    party.median.2D = median(coord2D, na.rm = TRUE)
  ) %>%
  ungroup() %>%
  group_by(session) %>%
  mutate(
    floor.median.1D = median(coord1D, na.rm = TRUE),
    floor.median.2D = median(coord2D, na.rm = TRUE)
  ) %>%
  ungroup() %>%
  mutate(
    mp_party_dist1 = abs(party.median.1D - coord1D),
    mp_party_dist2 = abs(party.median.2D - coord2D),
    mp_floor_dist1 = abs(floor.median.1D - coord1D),
    mp_floor_dist2 = abs(floor.median.2D - coord2D)
  ) %>%
  ungroup()

# Govt MPs
govt1991 <- c("Sjálfstæðisflokkur", "Alþýðuflokkur")
govt1995 <- c("Sjálfstæðisflokkur", "Framsóknarflokkur")
govt2007 <- c("Sjálfstæðisflokkur", "Samfylkingin")
govt2009 <- c("Vinstrihreyfingin - grænt framboð", "Samfylkingin")
govt2013 <- c("Sjálfstæðisflokkur", "Framsóknarflokkur")
govt2016 <- c("Sjálfstæðisflokkur", "Björt framtíð", "Viðreisn")
govt2017 <- c("Sjálfstæðisflokkur", "Vinstrihreyfingin - grænt framboð", "Framsóknarflokkur")

# Create gov't parties
bills_and_motions <- bills_and_motions %>%
  mutate(govtmp1 = case_when(
    party %in% govt1991 & session>=114 & session<=118 ~ 1,
    party %in% govt1995 & session>=119 & session<=133 ~ 1,
    party %in% govt2007 & session>=134 & session<=136 ~ 1,
    party %in% govt2009 & session>=136 & session<=141 ~ 1,
    party %in% govt2013 & session>=142 & session<=145 ~ 1,
    party %in% govt2016 & session>=146 & session<=147 ~ 1,
    party %in% govt2017 & session>=148 & session<=154 ~ 1,
    TRUE ~ 0
  ))

i <-1
for (i in 1:3) {
bills_and_motions <- bills_and_motions %>%
  mutate("govt_party_{i}" := case_when (
    session>=114 & session<=118 ~ govt1991[i],
    session>=119 & session<=133 ~ govt1995[i],
    session>=134 & session<=136 ~ govt2007[i],
    session>=136 & session<=141 ~ govt2009[i],
    session>=142 & session<=145 ~ govt2013[i],
    session>=146 & session<=147 ~ govt2016[i],
    session>=148 & session<=154 ~ govt2017[i])
      )
  i <- i+1
}

# Find max number of days in session
bills_and_motions <- bills_and_motions %>%
  group_by(session) %>%
  mutate(max_no_days = max(no_days.x)) %>%
  ungroup()

# Rescale Days
bills_and_motions$no_days.x <- bills_and_motions$no_days.x/30

bills_and_motions$session.factor <- factor(bills_and_motions$session)
sponsor_data_bills$session.factor <- factor(sponsor_data_bills$session)
sponsor_data_motions$session.factor <- factor(sponsor_data_motions$session)

# Number of bills
table(sponsor_data_bills$no_bills)
sum(sponsor_data_bills$no_bills)

# Number of motions
table(sponsor_data_motions$no_motions)
sum(sponsor_data_motions$no_motions)

bills_and_motions$xb <- ifelse(bills_and_motions$partyid==2,1,0)
bills_and_motions$xd <- ifelse(bills_and_motions$partyid==35,1,0)
bills_and_motions$xs <- ifelse(bills_and_motions$partyid==38,1,0)
bills_and_motions$xv <- ifelse(bills_and_motions$partyid==23,1,0)
bills_and_motions$xab <- ifelse(bills_and_motions$partyid==21,1,0)
bills_and_motions$xp <- ifelse(bills_and_motions$partyid==43,1,0)
bills_and_motions$xm <- ifelse(bills_and_motions$partyid==47,1,0)
bills_and_motions$xk <- ifelse(bills_and_motions$partyid==39,1,0)
bills_and_motions$xa <- ifelse(bills_and_motions$partyid==27,1,0)

# Change name to make table easier to create
bills_and_motions <- bills_and_motions %>%
  rename(mp_p_dist1 = mp_party_dist1, mp_p_dist2 = mp_party_dist2)

# Random slope models configuration
ctrl <- glmmTMBControl(
  optim = optim,
  optArgs = list(method = "BFGS"),
  optCtrl = list(maxit = 10000)
)

################################################################################################
#### MODELS
################################################################################################

bills_and_motions %>% 
  group_by(govtmp1) %>% 
  summarise("meanbills" = mean(age, na.rm = TRUE))

################################################################################################
# TABLE 1: Main Models
################################################################################################

oppositionmpsbills.fac_1 <- glmmTMB(
  no_bills ~ mp_p_dist2 + primary + last_in + gender +  age + rural + no_days.x + party + session.factor+
    (mp_p_dist2 -1 | session.factor ),        
  family = nbinom2,
  data = subset(bills_and_motions, govtmp1 == 0),
  control = ctrl
)

govmpsbills.fac_1 <- glmmTMB(
  no_bills ~ mp_p_dist2 + primary + last_in + gender + age + rural + no_days.x + party +session.factor+
    (mp_p_dist2 -1 | session.factor ),
  family = nbinom2,
  data = subset(bills_and_motions, govtmp1 == 1),
  control = ctrl
)

oppositionmpsmotions.fac_1 <- glmmTMB(
  no_motions ~ mp_p_dist2 + primary + last_in + gender + age + rural + no_days.x + party + session.factor+
    (mp_p_dist2 -1 | session.factor ),        
  family = nbinom2,
  data = subset(bills_and_motions, govtmp1 == 0),
  control = ctrl
)

govmpsmotions.fac_1 <- glmmTMB(
  no_motions ~ mp_p_dist2 + primary + last_in + gender + age + rural + no_days.x + party + session.factor +
    (mp_p_dist2  -1| session.factor ),
  family = nbinom2,
  data = subset(bills_and_motions, govtmp1 == 1),
  control = ctrl
)

################################################################################################
#### Output Table 1
################################################################################################

texreg(list(oppositionmpsbills.fac_1,govmpsbills.fac_1,oppositionmpsmotions.fac_1,govmpsmotions.fac_1),
       caption= "\\sc Private Members' Bills \\& Parliamentary Motions Introduced \\\\ \\small \\sc ---By Government \\& Opposition MPs---",
       label = "tab:proposals",
       reorder.coef = c(7, 3, 2, 5, 6, 4, 8, 1),
       use.packages = FALSE,
       booktabs = TRUE,
       float.pos = "H",
       stars = c(0.01, 0.05, 0.10),
       custom.coef.names = c("\\sc  Constant","\\sc Ideol.~Dist.: Rural", "\\sc Contested Primary","\\sc Last Seat In", "\\sc  Female", "\\sc  Age","\\sc Rural", "\\sc No.~Months"),
       omit.coef = "(session)|(party)",
       custom.header = list("\\sc Private Members' Bills" = 1:2, "\\sc Parliamentary Motions" = 3:4),
       custom.model.names = c("\\sc Opposition MP","\\sc Government MP","\\sc Opposition MP","\\sc Government MP"),
       custom.gof.names = c("AIC","\\sc Log Likelihood","\\sc Obs.","\\sc Sessions","\\sc Var(Ideol.Dist)"),
       custom.gof.rows = list("\\small\\sc Party \\& Session Fixed Eff." = c("\\(\\checkmark\\)", "\\(\\checkmark\\)", "\\(\\checkmark\\)", "\\(\\checkmark\\)")),
       custom.note = "%stars. Standard errors in parentheses.",
       file="PMB paper/tables/PMB_RE.tex")






################################################################################################
# APPENDIX A: LAST SEAT IN AND IDEOLOGY
################################################################################################

oppositionmpsbills.fac_1 <- glmmTMB(
  no_bills ~ mp_p_dist2 * last_in + primary + gender + age + rural + no_days.x + party + session.factor +
    (mp_p_dist2 -1 | session.factor ),        
  family = nbinom2,
  data = subset(bills_and_motions, govtmp1 == 0),
  control = ctrl
)

govmpsbills.fac_1 <- glmmTMB(
  no_bills ~ mp_p_dist2 * last_in + primary + gender + age + rural + no_days.x + party + session.factor +
    (mp_p_dist2 -1 | session.factor ),
  family = nbinom2,
  data = subset(bills_and_motions, govtmp1 == 1),
  control = ctrl
)

oppositionmpsmotions.fac_1 <- glmmTMB(
  no_motions ~ mp_p_dist2 * last_in + primary + gender + age + rural + no_days.x + party + session.factor+
    (mp_p_dist2 -1 | session.factor ),        
  family = nbinom2,
  data = subset(bills_and_motions, govtmp1 == 0),
  control = ctrl
)

govmpsmotions.fac_1 <- glmmTMB(
  no_motions ~ mp_p_dist2 * last_in + primary + gender + age + rural + no_days.x + party + session.factor +
    (mp_p_dist2  -1| session.factor ),
  family = nbinom2,
  data = subset(bills_and_motions, govtmp1 == 1),
  control = ctrl
)

################################################################################################
#### Output Table A.2
################################################################################################

texreg(list(oppositionmpsbills.fac_1,govmpsbills.fac_1,oppositionmpsmotions.fac_1,govmpsmotions.fac_1),
       caption= "\\sc Private Members' Bills \\& Parliamentary Motions Introduced \\\\ \\small \\sc ---By Government \\& Opposition MPs---",
       label = "tab:lastinideology",
       stars = c(0.01, 0.05, 0.10),
       float.pos = "H",
       use.packages = FALSE,
       booktabs = TRUE,
       scalebox = TRUE,
       reorder.coef = c(2, 3, 9, 4, 5, 6, 7, 8, 1),
       custom.coef.names = c("\\sc  Constant", "\\sc Ideol.~Dist.: Rural","\\sc Last In","\\sc Primary",
                             "\\sc  Female", "\\sc  Age", "\\sc Rural",
                             "\\sc No.~Months","\\sc Ideol.~Dist.: Rural * Last In"),
       omit.coef = "(session)|(party)",
       custom.header = list("\\sc Private Members' Bills" = 1:2, "\\sc Parliamentary Motions" = 3:4),
       custom.model.names = c("\\sc Opposition MP","\\sc Government MP","\\sc Opposition MP","\\sc Government MP"),
       custom.gof.names = c("AIC","\\sc Log Likelihood","\\sc Obs.","\\sc Sessions","\\sc Var(Ideol.Dist)"),
       custom.note = "%stars. Standard errors in parentheses.",
       file="PMB paper/tables/PMB_RE_LI_ID.tex")

#############################################################
### Appendix A: W/Primary * last_in interaction
#############################################################

oppositionmpsbills.fac_1 <- glmmTMB(
  no_bills ~ mp_p_dist2 + primary * last_in + gender + age + rural + no_days.x + party + session.factor+
    (mp_p_dist2 -1 | session.factor ),        
  family = nbinom2,
  data = subset(bills_and_motions, govtmp1 == 0),
  control = ctrl
)

govmpsbills.fac_1 <- glmmTMB(
  no_bills ~ mp_p_dist2 + primary * last_in + gender + age + rural + no_days.x + party +session.factor+
    (mp_p_dist2 -1 | session.factor ),
  family = nbinom2,
  data = subset(bills_and_motions, govtmp1 == 1),
  control = ctrl
)

oppositionmpsmotions.fac_1 <- glmmTMB(
  no_motions ~ mp_p_dist2 + primary * last_in + gender + age + rural + no_days.x + party + session.factor+
    (mp_p_dist2 -1 | session.factor ),        
  family = nbinom2,
  data = subset(bills_and_motions, govtmp1 == 0),
  control = ctrl
)

govmpsmotions.fac_1 <- glmmTMB(
  no_motions ~ mp_p_dist2 + primary * last_in + gender + age + rural + no_days.x + party + session.factor +
    (mp_p_dist2  -1| session.factor ),
  family = nbinom2,
  data = subset(bills_and_motions, govtmp1 == 1),
  control = ctrl
)

################################################################################################
#### Output Table A.3
################################################################################################

texreg(list(oppositionmpsbills.fac_1,govmpsbills.fac_1,oppositionmpsmotions.fac_1,govmpsmotions.fac_1),
       caption= "\\sc Private Members' Bills \\& Parliamentary Motions Introduced \\\\ \\small \\sc ---By Government \\& Opposition MPs---",
       label = "tab:primarylastin",
       stars = c(0.01, 0.05, 0.10),
       use.packages = FALSE,
       booktabs = TRUE,
       float.pos = "H",
       reorder.coef = c(3, 4, 9, 2, 7, 8, 5, 6, 1),
       custom.coef.names = c("\\sc  Constant", "\\sc Ideol.~Dist.: Rural","\\sc Primary","\\sc Last Seat In","\\sc  Female", "\\sc  Age", "\\sc Rural","\\sc No.~Months","\\sc Primary * Last In"),
       omit.coef = "(session)|(party)",
       custom.header = list("\\sc Private Members' Bills" = 1:2, "\\sc Parliamentary Motions" = 3:4),
       custom.model.names = c("\\sc Opposition MP","\\sc Government MP","\\sc Opposition MP","\\sc Government MP"),
       custom.gof.names = c("AIC","\\sc Log Likelihood","\\sc Obs.","\\sc Sessions","\\sc Var(Ideol.Dist)"),
       custom.note = "%stars. Standard errors in parentheses.",
       file="PMB paper/tables/PMB_RE_LI_PRIM.tex")


################################################################################################
# APPENDIX B: No Rural
################################################################################################

oppositionmpsbills.fac_1 <- glmmTMB(
  no_bills ~ mp_p_dist2 + primary + last_in + gender + age + no_days.x + party + session.factor+
    (mp_p_dist2 -1 | session.factor ),        
  family = nbinom2,
  data = subset(bills_and_motions, govtmp1 == 0),
  control = ctrl
)

govmpsbills.fac_1 <- glmmTMB(
  no_bills ~ mp_p_dist2 + primary + last_in + gender + age  + no_days.x + party +session.factor+
    (mp_p_dist2 -1 | session.factor ),
  family = nbinom2,
  data = subset(bills_and_motions, govtmp1 == 1),
  control = ctrl
)

oppositionmpsmotions.fac_1 <- glmmTMB(
  no_motions ~ mp_p_dist2 + primary + last_in + gender + age  + no_days.x + party + session.factor+
    (mp_p_dist2 -1 | session.factor ),        
  family = nbinom2,
  data = subset(bills_and_motions, govtmp1 == 0),
  control = ctrl
)

govmpsmotions.fac_1 <- glmmTMB(
  no_motions ~ mp_p_dist2 + primary + last_in + gender + age  + no_days.x + party + session.factor +
    (mp_p_dist2  -1| session.factor ),
  family = nbinom2,
  data = subset(bills_and_motions, govtmp1 == 1),
  control = ctrl
)

################################################################################################
#### Output Table B.4
################################################################################################

texreg(list(oppositionmpsbills.fac_1,govmpsbills.fac_1,oppositionmpsmotions.fac_1,govmpsmotions.fac_1),
       caption= "\\sc Private Members' Bills \\& Parliamentary Motions Introduced \\\\ \\small \\sc --- By Government \\& Opposition MPs ---\\\\ \\small \\sc --- Excluding Rural Indicator ---",
       label = "tab:norural",
       stars = c(0.01, 0.05, 0.10),
       float.pos = "H",
       use.packages = FALSE,
       booktabs = TRUE,
       #reorder.coef = c(7, 8, 4, 5, 2, 3, 6, 1),
       custom.coef.names = c("\\sc  Constant", "\\sc Ideol.~Dist.: Rural","\\sc Primary","\\sc Last Seat In","\\sc Female", "\\sc  Age",
                             "\\sc No.~Months"),
       omit.coef = "(session)|(party)",
       custom.header = list("\\sc Private Members' Bills" = 1:2, "\\sc Parliamentary Motions" = 3:4),
       custom.model.names = c("\\sc Opposition MP","\\sc Government MP","\\sc Opposition MP","\\sc Government MP"),
       custom.gof.names = c("AIC","\\sc Log Likelihood","\\sc Obs.","\\sc Sessions","\\sc Var(Ideol.Dist)"),
       custom.note = "%stars. Standard errors in parentheses.",
       file="PMB paper/tables/PMB_RE_NO_RURAL.tex")


#############################################################
### Appendix C: FULL MODEL W/GOVT-OPPOSITION INTERACTION
#############################################################

bills_and_motions$sessionGO <- bills_and_motions$govtmp*1000+bills_and_motions$session
bills_and_motions$sessionGO.factor <- factor(bills_and_motions$sessionGO)


#bills_and_motions <- subset(bills_and_motions,select=-c(govt_parties_list))

allmpsbills.fac_1 <- glmmTMB(
  no_bills ~ mp_p_dist2*govtmp1 + primary*govtmp1 + last_in*govtmp1 + gender*govtmp1 + age*govtmp1 + rural*govtmp1 + no_days.x*govtmp1 + party + sessionGO.factor+
    (mp_p_dist2 -1 | sessionGO.factor ),        
  family = nbinom2,
  data = bills_and_motions,
  control = ctrl
)

# Calculate marginal effect of gov't MP on # of bills
avg_slopes(allmpsbills.fac_1,variables="govtmp1")

### Repeat for test w/o random slopes
### W/O Random effects for average slopes
allmpsbills.fac_1t <- glmmTMB(
  no_bills ~ mp_p_dist2*govtmp1 + primary*govtmp1 + last_in*govtmp1 + gender*govtmp1 + age*govtmp1 + rural*govtmp1 + no_days.x*govtmp1 + party + sessionGO.factor+
    (mp_p_dist2 -1 | sessionGO.factor ),        
  family = nbinom2,
  data = bills_and_motions,
  control = ctrl
)

# Calculate marginal effect of gov't MP on # of motions
avg_slopes(allmpsbills.fac_1t,variables="govtmp1")

#Motions

allmpsmotions.fac_1 <- glmmTMB(
  no_motions ~ mp_p_dist2*govtmp1 + primary*govtmp1 + last_in*govtmp1 + gender*govtmp1 + age*govtmp1 + rural*govtmp1 + no_days.x*govtmp1 + party + sessionGO.factor+
    (mp_p_dist2 -1 | sessionGO.factor ),        
  family = nbinom2,
  data = bills_and_motions,
  control = ctrl
)

# Calculate marginal effect of gov't MP on # of motions
avg_slopes(allmpsmotions.fac_1,variables="govtmp1")

### Repeat for test w/o random slopes
### W/O Random effects for average slopes
allmpsmotions.fac_1t <- glmmTMB(
  no_motions ~ mp_p_dist2*govtmp1 + primary*govtmp1 + last_in*govtmp1 + gender*govtmp1 + age*govtmp1 + rural*govtmp1 + no_days.x*govtmp1 + party + sessionGO.factor,        
  family = nbinom2,
  data = bills_and_motions,
  control = ctrl
)

# Calculate marginal effect of gov't MP on # of motions
avg_slopes(allmpsmotions.fac_1t,variables="govtmp1")

################################################################################################
#### Output Table C.5
################################################################################################

texreg(list(allmpsbills.fac_1,allmpsmotions.fac_1),
       caption= "\\sc Private Members' Bills \\& Parliamentary Motions Introduced",
       label = "tab:govoppint",
       stars = c(0.01, 0.05, 0.10),
       float.pos = "H",
       use.packages = FALSE,
       booktabs = TRUE,
       #reorder.coef = c(7, 8, 4, 5, 2, 3, 6, 1),
       custom.coef.names = c("\\sc  Constant", "\\sc Ideol.~Dist.: Rural","\\sc Gov't MP","\\sc Primary",
                             "\\sc Last In", "\\sc  Female", "\\sc  Age","\\sc Rural","\\sc No.~Months",
                             "\\sc Gov't MP * Ideol.~Dist.: Rural","\\sc Gov't MP * Primary",
                             "\\sc Gov't MP * Last Seat In", "\\sc Gov't MP * Female", "\\sc  Gov't MP * Age",
                             "\\sc Gov't MP * Rural","\\sc Gov't MP * No.~Months"),
       omit.coef = "(session)|(party)",
       #custom.header = list("\\sc Private Members' Bills" = 1:2, "\\sc Parliamentary Motions" = 3:4),
       custom.model.names = c("\\sc Bills","\\sc Motions"),
       custom.gof.names = c("AIC","\\sc Log Likelihood","\\sc Obs.","\\sc Sessions","\\sc Var(Ideol.Dist)"),
       custom.note = "%stars. Standard errors in parentheses.",
       file="PMB paper/tables/int_govopp.tex")



#############################################################
### Appendix D: EFFECTS OF DISTRICT MAGNITUDE
#############################################################

oppositionmpsbills.fac_1 <- glmmTMB(
  no_bills ~ mp_p_dist2 + primary + last_in + gender + age + rural + no_days.x + party + session.factor + district_magnitude +
    (mp_p_dist2 -1 | session.factor ),        
  family = nbinom2,
  data = subset(bills_and_motions, govtmp1 == 0),
  control = ctrl
)

govmpsbills.fac_1 <- glmmTMB(
  no_bills ~ mp_p_dist2 + primary + last_in + gender + age + rural + no_days.x + party +session.factor+ district_magnitude +
    (mp_p_dist2 -1 | session.factor ),
  family = nbinom2,
  data = subset(bills_and_motions, govtmp1 == 1),
  control = ctrl
)

oppositionmpsmotions.fac_1 <- glmmTMB(
  no_motions ~ mp_p_dist2 + primary + last_in + gender + age + rural + no_days.x + party + session.factor + district_magnitude +
    (mp_p_dist2 -1 | session.factor ),        
  family = nbinom2,
  data = subset(bills_and_motions, govtmp1 == 0),
  control = ctrl
)

govmpsmotions.fac_1 <- glmmTMB(
  no_motions ~ mp_p_dist2 + primary + last_in + gender + age + rural + no_days.x + party + session.factor + district_magnitude +
    (mp_p_dist2  -1| session.factor ),
  family = nbinom2,
  data = subset(bills_and_motions, govtmp1 == 1),
  control = ctrl
)

################################################################################################
#### Output Table D.6
################################################################################################

texreg(list(oppositionmpsbills.fac_1,govmpsbills.fac_1,oppositionmpsmotions.fac_1,govmpsmotions.fac_1),
       caption= "\\sc Private Members' Bills \\& Parliamentary Motions Introduced \\\\ \\small \\sc ---By Government \\& Opposition MPs--- \\\\ \\small \\sc --- District Magnitude ---",
       label = "tab:dm",
       stars = c(0.01, 0.05, 0.10),
       use.packages = FALSE,
       booktabs = TRUE,
       float.pos = "H",
       #reorder.coef = c(7, 8, 4, 5, 2, 3, 6, 1),
       custom.coef.names = c("\\sc  Constant","\\sc Ideol.~Dist.: Rural","\\sc Primary","\\sc Last Seat In", "\\sc  Female", "\\sc  Age", "\\sc Rural", "\\sc No.~Months","\\sc District Magnitude"),
       omit.coef = "(session)|(party)",
       custom.header = list("\\sc Private Members' Bills" = 1:2, "\\sc Parliamentary Motions" = 3:4),
       custom.model.names = c("\\sc Opposition MP","\\sc Government MP","\\sc Opposition MP","\\sc Government MP"),
       custom.gof.names = c("AIC","\\sc Log Likelihood","\\sc Obs.","\\sc Sessions","\\sc Var(Ideol.Dist)"),
       custom.note = "%stars. Standard errors in parentheses.",
       file="PMB paper/tables/PMB_RE_DM.tex")





#############################################################
### Appendix E: Models w/ideological distance from coalition
#############################################################

# first, list of govt parties per session
govt_parties <- bills_and_motions %>%
  dplyr::select(session, govt_party_1, govt_party_2, govt_party_3) %>%
  pivot_longer(cols = starts_with("govt_party"), values_to = "govt_party") %>%
  filter(!is.na(govt_party)) %>%
  group_by(session) %>%
  summarise(govt_parties_list = list(unique(govt_party)), .groups="drop")

# create largest ideological distance between MP and any of the party medians in the coalition (1D and 2D)
bills_and_motions <- bills_and_motions %>%
  left_join(govt_parties, by = "session") %>%
  rowwise() %>%
  mutate(
    in_govt = party %in% govt_parties_list,
    
    largest_dist_1D = if (in_govt) {
      max(abs(coord1D - party.median.1D[party %in% govt_parties_list]))
    } else {
      opp_parties <- setdiff(unique(party[session == session]), govt_parties_list)
      max(abs(coord1D - party.median.1D[party %in% opp_parties]))
    },
    
    largest_dist_2D = if (in_govt) {
      max(abs(coord2D - party.median.2D[party %in% govt_parties_list]))
    } else {
      opp_parties <- setdiff(unique(party[session == session]), govt_parties_list)
      max(abs(coord2D - party.median.2D[party %in% opp_parties]))
    }
  ) %>%
  ungroup()

# fix age variable
bills_and_motions$age_int <- as.numeric(bills_and_motions$age)

# 1D bill
oppositionmpsbills.fac_1 <- glmmTMB(
  no_bills ~ largest_dist_1D + primary + last_in + gender + age_int + rural + no_days.x + party + session.factor+
    (largest_dist_1D -1 | session.factor ),        
  family = nbinom2,
  data = subset(bills_and_motions, govtmp1 == 0),
  control = ctrl
)

govmpsbills.fac_1 <- glmmTMB(
  no_bills ~ largest_dist_1D + primary + last_in + gender + age_int + rural + no_days.x + party +session.factor+
    (largest_dist_1D -1 | session.factor ),
  family = nbinom2,
  data = subset(bills_and_motions, govtmp1 == 1),
  control = ctrl
)

# 2D bill
oppositionmpsbills.fac_2 <- glmmTMB(
  no_bills ~ largest_dist_2D + primary + last_in + gender + age_int + rural + no_days.x + party + session.factor+
    (largest_dist_2D -1 | session.factor ),        
  family = nbinom2,
  data = subset(bills_and_motions, govtmp1 == 0),
  control = ctrl
)

govmpsbills.fac_2 <- glmmTMB(
  no_bills ~ largest_dist_2D + primary + last_in + gender + age_int + rural + no_days.x + party +session.factor+
    (largest_dist_2D -1 | session.factor ),
  family = nbinom2,
  data = subset(bills_and_motions, govtmp1 == 1),
  control = ctrl
)

# 1D motion
oppositionmpsmotions.fac_1 <- glmmTMB(
  no_motions ~ largest_dist_1D + primary + last_in + gender + age_int + rural + no_days.x + party + session.factor+
    (largest_dist_1D -1 | session.factor ),        
  family = nbinom2,
  data = subset(bills_and_motions, govtmp1 == 0),
  control = ctrl
)

govmpsmotions.fac_1 <- glmmTMB(
  no_motions ~ largest_dist_1D + primary + last_in + gender + age_int + rural + no_days.x + party + session.factor +
    (largest_dist_1D  -1| session.factor ),
  family = nbinom2,
  data = subset(bills_and_motions, govtmp1 == 1),
  control = ctrl
)


# 2D motion

oppositionmpsmotions.fac_2 <- glmmTMB(
  no_motions ~ largest_dist_2D + primary + last_in + gender + age_int + rural + no_days.x + party + session.factor+
    (largest_dist_2D -1 | session.factor ),        
  family = nbinom2,
  data = subset(bills_and_motions, govtmp1 == 0),
  control = ctrl
)

govmpsmotions.fac_2 <- glmmTMB(
  no_motions ~ largest_dist_2D + primary + last_in + gender + age_int + rural + no_days.x + party + session.factor +
    (largest_dist_2D  -1| session.factor ),
  family = nbinom2,
  data = subset(bills_and_motions, govtmp1 == 1),
  control = ctrl
)

################################################################################################
#### Output Table E.7
################################################################################################

texreg(list(govmpsbills.fac_1,govmpsbills.fac_2,govmpsmotions.fac_1,govmpsmotions.fac_2),
       caption= "\\sc Private Members' Bills \\& Parliamentary Motions Introduced \\\\ \\small \\sc ---By Government MPs \\& Ideological Distance From Partners---",
       label = "tab:coalition",
       reorder.coef = c(2, 9, 3, 4, 5, 6, 7, 8, 1),
       custom.coef.names = c("\\sc  Constant","\\sc Ideol.~Dist.: Soc-Econ","\\sc Primary", "\\sc Last Seat In","\\sc  Female", "\\sc  Age",
                             "\\sc Rural","\\sc No.~Months","\\sc Ideol.~Dist.: Rural"),
       omit.coef = "(session)|(party)",
       stars = c(0.01, 0.05, 0.10),
       custom.header = list("\\sc Private Members' Bills" = 1:2, "\\sc Parliamentary Motions" = 3:4),
       custom.model.names = c("\\sc \\small Socio-Economic","\\sc \\small Urban-Rural","\\sc \\small Socio-Economic","\\sc \\small Urban-Rural"),
       custom.gof.names = c("AIC","\\sc Log Likelihood","\\sc Obs.","\\sc Sessions","\\sc Var(Ideol.Dist.:S-E)","\\sc Var(Ideol.Dist.:Rural)"),
       custom.gof.rows = list("\\sc Party \\& Session Fixed Effects" = c("\\(\\checkmark\\)", "\\(\\checkmark\\)", "\\(\\checkmark\\)", "\\(\\checkmark\\)")),
       booktabs = TRUE,use.packages = FALSE,
       custom.note = "%stars. Standard errors in parentheses.",
       file="PMB paper/tables/PMB_RE_COALITION.tex")





#############################################################
### Appendix F: MODELS W/Party dummies
#############################################################

bills_and_motions$xb <- ifelse(bills_and_motions$partyid==2,1,0)
bills_and_motions$xd <- ifelse(bills_and_motions$partyid==35,1,0)
bills_and_motions$xs <- ifelse(bills_and_motions$partyid==38,1,0)
bills_and_motions$xv <- ifelse(bills_and_motions$partyid==23,1,0)
bills_and_motions$xab <- ifelse(bills_and_motions$partyid==21,1,0)
bills_and_motions$xp <- ifelse(bills_and_motions$partyid==43,1,0)
bills_and_motions$xm <- ifelse(bills_and_motions$partyid==47,1,0)
bills_and_motions$xk <- ifelse(bills_and_motions$partyid==39,1,0)
bills_and_motions$xa <- ifelse(bills_and_motions$partyid==27,1,0)

oppositionmpsbills.fac_1 <- glmmTMB(
  no_bills ~ mp_p_dist2 + primary + last_in + gender + age + rural + no_days.x + xd + xb + xs + xv + xa + xab + xp + xk + session.factor+
    (mp_p_dist2 -1 | session.factor ),        
  family = nbinom2,
  data = subset(bills_and_motions, govtmp1 == 0),
  control = ctrl
)

govmpsbills.fac_1 <- glmmTMB(
  no_bills ~ mp_p_dist2 + primary + last_in + gender + age + rural + no_days.x + xd + xb + xs + xv + xa + xab + xp + xk +session.factor+
    (mp_p_dist2 -1 | session.factor ),
  family = nbinom2,
  data = subset(bills_and_motions, govtmp1 == 1),
  control = ctrl
)

oppositionmpsmotions.fac_1 <- glmmTMB(
  no_motions ~ mp_p_dist2 + primary + last_in + gender + age + rural + no_days.x + xd + xb + xs + xv + xa + xab + xp + xk + session.factor+
    (mp_p_dist2 -1 | session.factor ),        
  family = nbinom2,
  data = subset(bills_and_motions, govtmp1 == 0),
  control = ctrl
)

govmpsmotions.fac_1 <- glmmTMB(
  no_motions ~ mp_p_dist2 + primary + last_in + gender + age + rural + no_days.x + xd + xb + xs + xv + xa + xab + xp + xk + session.factor +
    (mp_p_dist2  -1| session.factor ),
  family = nbinom2,
  data = subset(bills_and_motions, govtmp1 == 1),
  control = ctrl
)

################################################################################################
#### Output Table F.8
################################################################################################

texreg(list(oppositionmpsbills.fac_1,govmpsbills.fac_1,oppositionmpsmotions.fac_1,govmpsmotions.fac_1),
       caption= "\\sc Private Members' Bills \\& Parliamentary Motions Introduced \\\\ \\small \\sc ---By Government \\& Opposition MPs---",
       label = "tab:partydummy",
       stars = c(0.01, 0.05, 0.10),
       float.pos = "H",
       use.packages = FALSE,
       booktabs = TRUE,
       #reorder.coef = c(7, 8, 4, 5, 2, 3, 6, 1),
       custom.coef.names = c("\\sc  Constant", "\\sc Ideol.~Dist.: Rural","\\sc Primary","\\sc Last Seat Seat In","\\sc  Female", "\\sc  Age", "\\sc Rural","\\sc No.~Months",
                             "\\sc Independence Party","\\sc Progressive Party","\\sc Soc.~Democr.~Alliance","\\sc Left-Greens","\\sc Social Democr.~Party","\\sc People's Alliance","\\sc Pirate Party","\\sc Women's List"),
       omit.coef = "(session)",
       custom.header = list("\\sc Private Members' Bills" = 1:2, "\\sc Parliamentary Motions" = 3:4),
       custom.model.names = c("\\sc Opposition MP","\\sc Government MP","\\sc Opposition MP","\\sc Government MP"),
       custom.gof.names = c("AIC","\\sc Log Likelihood","\\sc Obs.","\\sc Sessions","\\sc Var(Ideol.Dist)"),
       custom.note = "%stars. Standard errors in parentheses.",
       file="PMB paper/tables/PMB_RE_WPARTY.tex")




#############################################################
### Appendix G: MPs' Choice Over Bills and Motions
#############################################################


bills_and_motions_permp <- bills_and_motions %>%
  group_by(mpid, govtmp1, session.factor) %>%
  summarise(
    no_bills   = sum(no_bills, na.rm = TRUE),
    no_motions = sum(no_motions, na.rm = TRUE),
    mp_p_dist2 = first(mp_p_dist2),
    primary = first(primary),
    last_in = first(last_in),
    gender = first(gender),
    age = first(age),
    no_days.x = first(no_days.x),
    party = first(party),
    rural = first(rural),
    .groups = "drop"
  )

bills_and_motions_long <- bills_and_motions_permp %>%
  pivot_longer(
    cols = c(no_bills, no_motions),
    names_to = "proposal_type",
    values_to = "count"
  ) %>%
  mutate(
    proposal_type = ifelse(proposal_type=="no_bills","bill","motion"),
    proposal_type = factor(proposal_type)
  )

# Table G.9 Within-Group Preference
bm_gov1 <- glmmTMB(
  count ~ proposal_type + session.factor,
  data = subset(bills_and_motions_long, govtmp1 == 1),
  family = nbinom2
)

bm_gov2 <- glmmTMB(
  count ~ proposal_type + session.factor +
    mp_p_dist2 + primary + last_in + gender + age + rural + no_days.x + party,
  data = subset(bills_and_motions_long, govtmp1 == 1),
  family = nbinom2
)

bm_opp1 <- glmmTMB(
  count ~ proposal_type + session.factor,
  data = subset(bills_and_motions_long, govtmp1 == 0),
  family = nbinom2
)

bm_opp2 <- glmmTMB(
  count ~ proposal_type + session.factor +
    mp_p_dist2 + primary + last_in + gender + age + rural + no_days.x + party,
  data = subset(bills_and_motions_long, govtmp1 == 0),
  family = nbinom2
)

texreg(list(bm_gov1, bm_gov2, bm_opp1, bm_opp2),
       caption= "\\sc Bills vs. Motions within Government \\& Opposition MPs\\\\ \\small \\sc (DV: Proposal Count)",
       label = "tab:govoppbm",
       stars = c(0.01, 0.05, 0.10),
       omit.coef = "(session\\.factor|party)",
       reorder.coef = c(2, 3, 4, 5, 6, 7, 8, 9, 1),
       custom.coef.names = c( "\\sc  Constant", "\\sc Proposal Type (Motion)", 
                              "\\sc Ideol.~Dist.: Rural", "\\sc Contested Primary","\\sc Last In", "\\sc  Female", "\\sc  Age",
                              "\\sc Rural", "\\sc No.~Months"),
       custom.header = list("\\sc Government MP" = 1:2, "\\sc Opposition MP" = 3:4),
       custom.model.names = c("\\sc Base Model","\\sc w/ Covariates", "\\sc Base Model","\\sc w/ Covariates"),
       custom.gof.names = c("AIC","\\sc Log Likelihood","\\sc Obs."),
       file="PMB paper/tables/gov_motion_opp_bill.tex")

# Table G.10 Interaction between Government MP and Motion

govoppbm1 <- glmmTMB(
  count ~ govtmp1 * proposal_type + session.factor,
  data = bills_and_motions_long,
  family = nbinom2,
  control = ctrl
)


govoppbm2 <- glmmTMB(
  count ~ govtmp1 * proposal_type + session.factor +
    mp_p_dist2 + primary + last_in + gender + age + rural + no_days.x + party,
  data = bills_and_motions_long,
  family = nbinom2,
  control = ctrl
)

texreg(list(govoppbm1, govoppbm2),
       caption= "\\sc Preference over Bills \\& Motions between Government \\& Opposition MPs\\\\ \\small \\sc (DV: Proposal Count)",
       label = "tab:govoppbm1",
       stars = c(0.01, 0.05, 0.10),
       float.pos = "H",
       omit.coef = "(session\\.factor|party)",
       reorder.coef = c(2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 1),
       custom.coef.names = c( "\\sc  Constant", "\\sc Government MP", "\\sc Proposal Type (Motion)", "\\sc Government $\\times$ Motion",
                              "\\sc Ideol.~Dist.: Rural", "\\sc Contested Primary","\\sc Last In", "\\sc  Female", "\\sc  Age",
                              "\\sc Rural", "\\sc No.~Months"),
       custom.model.names = c("\\sc Base Model","\\sc w/ Covariates"),
       custom.gof.names = c("AIC","\\sc Log Likelihood","\\sc Obs."),
       file="PMB paper/tables/gov_motion_opp_bill1.tex")